package com.richpencil.modules.sqlsearch.service.impl;


import com.richpencil.sqlsearch.SQLStatement;
import com.richpencil.sqlsearch.SQLStatementItem;
import com.richpencil.utils.StringHelper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class SQLStatementService {

    List<SQLStatement> l=Lists.newArrayList();
    HashMap<String, SQLStatement> map=new HashMap<String, SQLStatement>();
    public void init() throws SQLException {
        Map<String,Object> m= Maps.newHashMap();
        //l=dataEngine.SQL.queryForList("system_select_syssql",m);
        for(SQLStatement b:l) {
            //this.parseObject(b);
            map.put(b.fid,b);
        }
    }
    private void parseObject(SQLStatement bo)
    {
        if(bo!=null)
        {
            int nCount = StringUtils.countMatches(bo.fsqlstatement, "$");
            String search=bo.fsqlstatement;
            String[] array= StringHelper.getStringArray(search);
            List<String> fixs= Lists.newArrayList();
            List<String> sqls=Lists.newArrayList();
            int k=0;
            for(String s:array)
            {
                bo.array.add(s);
                fixs.add(s);
                sqls.add(s);
                if(StringHelper.checkIsIndexof(StringUtils.indexOfIgnoreCase(s, "$")))
                {
                    SQLStatementItem item=new SQLStatementItem();
                    int nextpos=-1;
                    if(k-1>=0)
                    {
                        fixs.remove(fixs.size()-1);
                        nextpos=StringHelper.SetOperateAfter(k-1, array, fixs, item);
                    }

                    if(nextpos>=0)
                    {
                        fixs.remove(fixs.size()-1);
                        item.fieldname=array[nextpos];
                        item.fieldvalue=s;
                        item.paramname=StringHelper.getParamName(s);
                        item.oldparamname="${"+item.paramname+"}";
                        nextpos--;
                    }
                    StringHelper.SetOperate(nextpos, array, fixs, item);
                    fixs.add(item.oldparamname);
                    bo.addItem(item);
                }
                k++;
            }
            bo.setFsqlstatement(Joiner.on(" ").join(sqls));
            bo.ffixsql=Joiner.on(" ").join(fixs);
        }
    }

    public static Map<String, Object> RequestParamToMap(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        for (Map.Entry<String, String[]> entry : request.getParameterMap()
                .entrySet()) {
            String[] arr = entry.getValue();
            String result = "";
            if (null != arr && arr.length > 0) {
                for (int i = 0; i < arr.length; i++) {
                    result += arr[i];
                    if (i < arr.length - 1) {
                        result += ",";
                    }
                }
                map.put(entry.getKey(), result);
            }
        }
        return map;
    }

    public String getSelectQuery(SQLStatement b, String key, HttpServletRequest request) {
        Map<String, Object> paramMap=RequestParamToMap(request);
        return getSelectQuery(b,key,map);
    }






    public String getSelectQuery(SQLStatement b, String key, Map paramMap)
    {
        String sqlstring=b.ffixsql;
        Iterator entries = paramMap.entrySet().iterator();
        while (entries.hasNext()) {

            Map.Entry entry = (Map.Entry) entries.next();
            String fkey=entry.getKey().toString();
            Object fvalue=entry.getValue();
            SQLStatementItem item=b.getSQLItem(fkey);
            if(!(StringHelper.IsEmptyOrNull(item)||StringHelper.IsEmptyOrNull(fvalue)))
            {
                sqlstring=StringUtils.replace(sqlstring, item.oldparamname, item.SQL(fvalue));
            }
            else
            {
                if(item!=null)
                {
                    sqlstring=StringUtils.replace(sqlstring, item.oldparamname, "");
                }
            }
        }
        return sqlstring;
    }

    public void getLog(SQLStatement b, String key)
    {
        StringBuilder builder=new StringBuilder();
        if(b==null)
        {
            builder.append("\r\n");
            builder.append("------FL------GenerateSql-----------------------------------------------------");
            builder.append("\r\n");
            builder.append("-----------FL------FsqlId----------------"+key+"------is not exists----------------");
            builder.append("\r\n");
        }
        else
        {
            builder.append("-----------FL------GenerateSql-----------------------------------------------------");
            builder.append("\r\n");
            builder.append("-----------FL------FsqlId-----------------------------"+key+"----------------------");
            builder.append("\r\n");
            builder.append("-----------FL------ffixsql----------------------------"+b.ffixsql+"----------------");
            builder.append("\r\n");
            builder.append("-----------FL------Pharse Array Start----------------------------------------------");
            builder.append("\r\n");
            for(String s:b.array)
            {
                builder.append("["+s+"]");
                builder.append("\r\n");
            }
            builder.append("-----------FL------Pharse Array  End-----------------------------------------------");
            builder.append("\r\n");
            builder.append("-----------FL------Final Sql-------------------------------------------------------");
            builder.append(b.ffinalsql);					}
        //this.log.error(builder.toString());
    }





}
